import axios from "axios";
import { Message } from "element-ui";
import { showLoading, hideLoading } from "@/plugins/element/loading/loading.js";
import Router from "@/router";
import { refreshToken } from "@/api/login/login.js";
import {
  getToken,
  isRefreshToken,
  setToken,
  removeToken,
} from "@/utils/token.js";

// 创建axios实例
const service = axios.create({
  baseURL: "/api",
  timeout: 30000,
});
let isRefreshing = false;
service.interceptors.request.use(
  (config) => {
    showLoading();
    // if (getToken() && isRefreshToken() && !isRefreshing) {
      // 判断是否在刷新
      isRefreshing = true;
      // let params = {
      //   refresh_token: localStorage.getItem("refresh_token"),
      // };
      // refreshToken(params)
      //   .then((res) => {
      //     setToken(res.data);
      //   })
      //   .finally(() => {
      //     isRefreshing = false;
      //   });
    // }
    // config.headers.common["Authorization"] = getToken();
    config.headers.common["Authorization"] = localStorage.getItem("Authorization");
    return config;
  },
  (error) => {
    console.log(error, "error");
    return error;
  }
);

service.interceptors.response.use(
  (response) => {
    hideLoading();
    const res = response.data;
     if (res.type && res.size) {
       //下载文件
       console.log(res);
       return response;
      } else {
      errorHandle(res);
      console.log(res.msg);
      return res;
    }
  },
  (error) => {
    const { response } = error;
    if (response) {
      
      errorHandle(response.data);
    } else {
      Message({
        message: "网络连接异常,请稍后再试!",
        type: "error",
        duration: 3000,
      });
    }
    hideLoading();
    return Promise.reject(error);
  }
);

function errorHandle(res) {
  // 状态码判断
  switch (res.code) {
    case 406:
    case 0:
      Message({
        message: res.msg,
        type: "success",
        duration: 3000,
      });
      break;
    case 400:
      Message({
        message: res.msg,
        type: "error",
        duration: 3000,
      });
      break;
    case 401:
      hideLoading();
      if (Router.history.current.path !== "/login") {
        Message({
          message: res.msg,
          type: "error",
          duration: 3000,
        });
        removeToken();
        Router.replace("/login" + "?redirect=" + Router.history.current.path);
      }
      break;
    case 403:
      Message({
        message: "您暂无权限",
        type: "error",
        duration: 3000,
      });
      break;
    case 404:
      Message({
        message: "请求的资源不存在",
        type: "error",
        duration: 3000,
      });
      break;
    default:
      Message({
        message: res.msg ? res.msg : "网络连接错误",
        type: "error",
        duration: 3000,
      });
  }
}

export default service;
